﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Secondhand_Book_Trade
{
    public partial class Login : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            
        }
        protected void Button1_Click(object sender, EventArgs e)
        {
            DataView dv = (DataView)SqlDataSource1.Select(DataSourceSelectArguments.Empty);
            int count = Convert.ToInt32(dv[0][0]);
            if (count > 0)
            {
                // 查询用户详细信息
                string username = txtUsername.Text.Trim();
                string role = ddlRole.SelectedValue;
                string connStr = System.Configuration.ConfigurationManager.ConnectionStrings["Secondhand_book_tradeConnectionString"].ConnectionString;
                using (var conn = new System.Data.SqlClient.SqlConnection(connStr))
                {
                    string sql = "SELECT UserID, Username, Nickname, Role, AvatarUrl, Email, Phone FROM Users WHERE Username=@Username AND Role=@Role";
                    var cmd = new System.Data.SqlClient.SqlCommand(sql, conn);
                    cmd.Parameters.AddWithValue("@Username", username);
                    cmd.Parameters.AddWithValue("@Role", role);
                    conn.Open();
                    var reader = cmd.ExecuteReader();
                    if (reader.Read())
                    {
                        Session["UserID"] = reader["UserID"];
                        Session["Username"] = reader["Username"];
                        Session["Nickname"] = reader["Nickname"];
                        Session["Role"] = reader["Role"];
                        Session["AvatarUrl"] = reader["AvatarUrl"];
                        Session["Email"] = reader["Email"];
                        Session["Phone"] = reader["Phone"];
                    }
                }

                // 跳转
                if (role == "0")
                    Response.Redirect("UserDashboard.aspx");
                else if (role == "1")
                    Response.Redirect("SellerDashboard.aspx");
                else if (role == "2")
                    Response.Redirect("AdminDashboard.aspx");
            }
            else
            {
                Response.Write("<script>alert('用户名或密码错误，或角色选择不正确！');</script>");
            }
        }
    }
}